package com;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.*;

public class PooledDayTimeServer2 {

    private final static int PORT = 1113;

    private final static int CORE_THREAD_NUM = 30;

    private final static int MAX_THREAD_NUM = 50;

    private final static int KEEP_ALIVE = 50;

    private final static TimeUnit UNIT = TimeUnit.SECONDS;

    private final static BlockingQueue<Runnable> QUEUE = new ArrayBlockingQueue<>(20);

    public static void main(String[] args) {

        ExecutorService tp = new ThreadPoolExecutor(CORE_THREAD_NUM,MAX_THREAD_NUM,KEEP_ALIVE,UNIT,QUEUE);

        try (ServerSocket serverSocket = new ServerSocket(PORT)){

            while (true) {

                Socket conn = serverSocket.accept();

                tp.execute(new PooledThread(conn));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static class PooledThread implements Runnable {

        private Socket conn;

        public PooledThread(Socket conn) {
            this.conn = conn;
        }

        @Override
        public void run() {

            try {

                Writer writer = new OutputStreamWriter(conn.getOutputStream());

                writer.write(new Date().toString() + "\r\n");

                writer.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }finally {

                try {
                    conn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
    }



}
